import time
import json
from flask import Flask, render_template, session, redirect, url_for, request, jsonify
from flask_cors import CORS
from flask_pymongo import PyMongo

app = Flask(__name__)
CORS(app, resources=r'/*')  # 注册CORS, "/*" 允许访问所有api

mongo = PyMongo(app, uri="mongodb://localhost:27017/pokemon")  # 开启数据库实例
pokedex = mongo.db.pokedex
USER = mongo.db.user
COLLECTION = mongo.db.collection
LIKE = mongo.db.like
COMMENTS = mongo.db.comments


# @app.route('/')
# def homepage():
#     page = int(request.args.get("page", 1))
#     # name=mongo.db.pokedex.find().skip((page-1)*page_size).limit(page_size)
#     # print(mongo.db.pokedex.count_documents({}))
#     pages, toal_page, page_con = get_page(page, pokedex)

#     return render_template('homepage.html', pokemons=page_con, pages=pages, toal_page=toal_page, page=page, p_page=page-1, l_page=page+1, h_p_page=page != 1, h_l_page=page != toal_page)


# @app.route('/login', methods=['GET', 'POST'])
# def login():
#     if request.method == "GET":
#         return render_template('login.html')
#     json_data = request.json
#     user_name = json_data['user_name']

#     user = mongo.db.user.find_one({"username": user_name})
#     if user and user["password"] == json_data['password']:
#         session['logged_in'] = True
#         session["user_name"] = user_name
#         session["user_type"] = user["type"]
#         status = True
#     else:
#         status = False
#     return jsonify({'result': status})


# @app.route("/session", methods=["GET"])
# def check_session():
#     """登录校验"""
#     username = session.get("username")
#     if username:
#         return jsonify(msg=username)
#     else:
#         return jsonify(msg="登录校验未通过")


# @app.route('/logout')
# def logout():
#     session.clear()
#     return jsonify(msg="退出登录成功")


# @app.route('/register', methods=['GET', 'POST'])
# def register():
#     if request.method == "GET":
#         return render_template('register.html')
#     json_data = request.json
#     try:

#         mongo.db.user.insert_one(
#             {"username": json_data['username'], "password": json_data['password'], "type": 0})  # 正常插入一条数据
#         status = True
#     except:
#         status = False
#     return jsonify({'result': status})


# @app.route('/get_list', methods=['GET'])
# def get_list():
#     page = request.args.get("page", 1)


def get_page(page, con, page_size=10, index=10, filter={}):
    """
    kws
        index 为显示可点击的页数,
        page 当前页
        con 查询对象
        page_size 页面大小

    return
        page_con 显示的内容
        pages_ 显示的页码
        toal_page 总页数
    """
    page_con = con.find(filter).skip(
        (page-1)*page_size).limit(page_size)  # 显示的页面内容
    count = con.count_documents(filter)  # 120
    if count % page_size:
        toal_page = int(count / page_size) + 1
    else:
        toal_page = int(count / page_size)
    pages = list(i for i in range(1, toal_page + 1))
    if (toal_page-index) <= page:

        pages_ = pages[page-int(index/2):page+int(index/2)]
    else:
        pages_ = (pages[page-int(index/2):page+int(index/2)])
    if len(pages_) < index:
        if page < index:
            pages_ = pages[:index]
        else:
            pages_ = pages[-index:]
    return pages_, toal_page, page_con


# @app.route('/search', methods=['GET'])
# def search():  # 搜索
#     stype = request.args.get("stype", '')
#     if not stype:
#         return jsonify(msg="搜索类型不能为空")
#     wd = request.args.get("wd", '')
#     page = int(request.args.get("page", 1))

#     if stype == "id":
#         wd = int(wd)
#     filter = {stype: wd}

#     pages, toal_page, page_con = get_page(page, pokedex, filter=filter)
#     return render_template('search.html', pokemons=page_con, pages=pages, toal_page=toal_page, page=page, p_page=page-1, l_page=page+1, h_p_page=page != 1, h_l_page=page != toal_page, wd=wd, stype=stype)

#     # return pages_, toal_page,page_con, stype,wd,page


@app.route('/api/test', methods=['GET'])
def test():  # 测试
    filter = {}

    pages, toal_page, page_con = get_page(1, pokedex, filter=filter)
    ls = []
    for i in page_con:
        n_d = {}
        for k, v in dict(i).items():

            if k != "_id":
                n_d[k] = v
        ls.append(n_d)
    return jsonify(
        {
            "stats": "ok",
            "datas": ls
        }
    )


@app.route('/api/login', methods=['GET', "POST"])
def login1():  #
    user = json.loads(request.get_data(), strict=False)['user']
    # print(user)
    su = USER.find_one({"username": user['username']})
    if su:
        # print(su,type(su))
        if su['password'] == user['password']:

            return jsonify({
                "status": "ok",
                "user": handle_con(su)
            })
        else:
            return jsonify({
                "status": "PASSWORD ERROR",
            })
    else:
        return jsonify({
            "status": "USER already exists",
        })


@app.route('/api/register', methods=['GET', "POST"])
def register1():  #
    user = json.loads(request.get_data(), strict=False)['user']
    # print(user)
    su = USER.find_one({"username": user['username']})
    if not su:
        # print(su,type(su))
        user.update({"type": 0})
        user.pop("password1")
        USER.insert_one(user)

        return jsonify({
            "status": "ok",
        })
    else:
        return jsonify({
            "status": "USER already exists",
        })


@app.route('/api/deleteuser', methods=['GET', "POST"])
def deleteuser():
    user = json.loads(request.get_data(), strict=False)['user']
    result = USER.delete_one(user)
    # print(result)
    return jsonify({
        "status": "ok",
    })


@app.route('/api/adduser', methods=['GET', "POST"])
def adduser():
    user = json.loads(request.get_data(), strict=False)['user']
    result = USER.insert_one(user)
    # print(result)
    return jsonify({
        "status": "ok",
    })


@app.route('/api/edituser', methods=['GET', "POST"])
def edituser():
    user = json.loads(request.get_data(), strict=False)['user']
    old_user= json.loads(request.get_data(), strict=False)['old_user']
    username = old_user
    result = USER.replace_one({'username': username}, user)
    # print(result)
    return jsonify({
        "status": "ok",
    })


@app.route('/api/get_pokemon', methods=['GET'])
def get_pokemon():
    p_id = request.args.get("id", None)
    if not id:
        return jsonify({
            "status": "don't have id",
        })
    pokemon = pokedex.find_one({'Id': p_id})
    if pokemon:
        pokemon = handle_con(pokemon)
        return jsonify({
            "status": "ok",
            "data": pokemon
        })
    else:
        return jsonify({
            "status": "don't have this",
        })


def handle_con(con):

    n_d = {}
    for k, v in con.items():

        if k != "_id":
            n_d[k] = v

    return n_d


def handle_page_con(page_con):
    ls = []
    for i in page_con:
        n_d = {}
        for k, v in dict(i).items():

            if k != "_id":
                n_d[k] = v
        ls.append(n_d)
    return ls


@app.route('/api/index')
def index():
    page = int(request.args.get("page", 1))
    # name=mongo.db.pokedex.find().skip((page-1)*page_size).limit(page_size)
    # print(mongo.db.pokedex.count_documents({}))
    pages, toal_page, page_con = get_page(page, pokedex)
    datas = handle_page_con(page_con)
    json_data = {"stats": "ok"}
    json_data.update({"datas": datas, "pages": pages, 'toal_page': toal_page, 'page': page,
                      "p_page": page-1, 'l_page': page+1, 'h_p_page': page != 1, 'h_l_page': page != toal_page})
    return jsonify(json_data)


@app.route('/api/search', methods=['GET'])
def search1():  # 搜索
    stype = request.args.get("stype", '')
    if not stype:
        return jsonify(msg="search type can't None")
    wd = request.args.get("wd", '')
    page = int(request.args.get("page", 1))

    # if stype=="id":
    #     wd=int(wd)
    filter = {stype: wd}
    if stype == "Type":
        filter = {"$or": [
            {"Type1": wd}, {'Type2': wd}
        ]
        }

    pages, toal_page, page_con = get_page(page, pokedex, filter=filter)
    # return render_template('search.html', pokemons=page_con,pages=pages,toal_page=toal_page,page=page,p_page=page-1,l_page=page+1,h_p_page=page!=1,h_l_page=page!=toal_page,wd=wd,stype=stype)
    datas = handle_page_con(page_con)
    json_data = {"stats": "ok"}
    json_data.update({"datas": datas, "pages": pages, 'toal_page': toal_page, 'page': page, "p_page": page-1,
                      'l_page': page+1, 'h_p_page': page != 1, 'h_l_page': page != toal_page, 'wd': wd, 'stype': stype})
    return jsonify(json_data)
    # return pages_, toal_page,page_con, stype,wd,page


@app.route('/api/userlist', methods=['GET'])
def getUserList():

    filter = {}
    userlist = USER.find()
    datas = handle_page_con(userlist)

    json_data = {"stats": "ok"}
    json_data.update({"datas": datas})
    return jsonify(json_data)
    # return pages_, toal_page,page_con, stype,wd,page


# @app.route('/api/like', methods=['POST'])
# def addLike():
#     like = {}
#     LIKE.insert_one(like)

#     json_data = {"stats": "ok"}
#     return jsonify(json_data)


# @app.route('/api/dislike', methods=['POST'])
# def disLike():
#     like = {}
#     LIKE.delete_one(like)

#     json_data = {"stats": "ok"}
#     return jsonify(json_data)


# @app.route('/api/addcomment', methods=['POST'])
# def addComments():
#     # comment=request.form['collection']
#     comment = json.loads(request.get_data(), strict=False)['collection']
#     COMMENTS.insert_one(comment)

#     json_data = {"stats": "ok"}
#     return jsonify(json_data)


# @app.route('/api/commentslist', methods=['GET'])
# def getCommentsList():

#     commentslist = COMMENTS.find()
#     datas = handle_page_con(commentslist)

#     json_data = {"stats": "ok"}
#     json_data.update({"datas": datas})
#     return jsonify(json_data)


# @app.route('/api/deletecomments', methods=['GET'])
# def deleteComment():
#     comment = json.loads(request.get_data(), strict=False)['collection']
#     result = COMMENTS.delete_one(comment)

#     json_data = {"stats": "ok"}
#     json_data.update({"datas": result})
#     return jsonify(json_data)

# 评论


@app.route('/api/add_comment', methods=['GET', "POST"])
# 添加评论
def comment():
    comment = json.loads(request.get_data(), strict=False)['comment']
    # print(COMMENTS.find().__dict__,COMMENTS.find().count())
    # c_id = COMMENTS.find().count()+1 #if have count()
    c_id = COMMENTS.count_documents({})+1 #python 3.10 flask 2.2.2
    comment.update({'id': c_id})
    comment.update({'time': time.strftime(
        '%Y-%m-%d %H:%M:%S', time.localtime(time.time()))})
    COMMENTS.insert_one(comment)
    return jsonify({
        "status": "ok"})


# 删除评论
@app.route('/api/del_comment', methods=["POST"])
def del_comment():
    c_id = json.loads(request.get_data(), strict=False)['id']
    # print(c_id)
    result = COMMENTS.delete_one({"id": int(c_id)})
    # print(result.deleted_count)
    return jsonify({
        "status": "ok"})

# 获取评论列表


@app.route('/api/get_commentArr', methods=['GET'])
def getcommentArr():
    p_id = request.args.get("id", None)
    commentArr = COMMENTS.find({"p_id": p_id})
    commentArr = handle_page_con(commentArr)
    return jsonify({
        "status": "ok",
        "data": commentArr
    })


@app.route('/api/like_comment', methods=["POST"])
def like_comment():
    c_id = json.loads(request.get_data(), strict=False)['id']
    username = json.loads(request.get_data(), strict=False)['username']
    comment = COMMENTS.find_one({'id': c_id})
    comment['like_user'].append(username)
    COMMENTS.replace_one({'id': c_id}, comment)
    return jsonify({
        "status": "ok",
        'username':username
    })


@app.route('/api/dislike_comment', methods=["POST"])
def dislike_comment():
    c_id = json.loads(request.get_data(), strict=False)['id']
    username = json.loads(request.get_data(), strict=False)['username']
    comment = COMMENTS.find_one({'id': c_id})
    # print(username)
    comment['like_user'].remove(username)
    COMMENTS.replace_one({'id': c_id}, comment)
    return jsonify({
        "status": "ok",
        'username':username
    })

# 收藏


@app.route('/api/discollection', methods=["POST"])
def discollection():
    p_id = json.loads(request.get_data(), strict=False)['id']
    username = json.loads(request.get_data(), strict=False)['username']
    user = USER.find_one({'username': username})
    # print(user['col_lis'])
    user['col_lis'].remove(p_id)
    USER.replace_one({'username': username}, user)
    return jsonify({
        "status": "ok",
        'data':p_id
    })


@app.route('/api/collection', methods=["POST"])
def collection():
    p_id = json.loads(request.get_data(), strict=False)['id']
    username = json.loads(request.get_data(), strict=False)['username']
    user = USER.find_one({'username': username})
    # print(username)
    # print(user['col_lis'])
    user['col_lis'].append(p_id)
    USER.replace_one({'username': username}, user)
    return jsonify({
        "status": "ok",
        'data':p_id
    })


@app.route('/api/get_user', methods=["POST"])
def get_user():
    username = json.loads(request.get_data(), strict=False)['username']
    user = USER.find_one({'username': username})
    user = handle_con(user)
    return jsonify({
        "status": "ok",
        'data': user
    })


if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
